package com.yp.infrastructure.axon.config;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.WildcardTypePermission;
import org.axonframework.serialization.xml.XStreamSerializer;

public class SecureXStreamSerializer extends XStreamSerializer{

    private static XStreamSerializer _instance;

    /**
     * Instantiate a {@link XStreamSerializer} based on the fields contained in the {@link Builder}. The {@link XStream}
     * instance is configured with several converters for the most common types in Axon.
     *
     * @param builder the {@link Builder} used to instantiate a {@link XStreamSerializer} instance
     */
    protected SecureXStreamSerializer(Builder builder) {
        super(builder);
    }

    public static XStreamSerializer get() {
        if (_instance == null) {
            _instance = secureXStreamSerializer();
        }
        return _instance;
    }

    private static XStreamSerializer secureXStreamSerializer() {
        String[] wildcardPackage = new String[]{"org.axonframework.**", "com.yp.**"};
        XStream xStream = new XStream();
        xStream.setClassLoader(SecureXStreamSerializer.class.getClassLoader());
        xStream.allowTypesByWildcard(wildcardPackage);
        WildcardTypePermission permission = new WildcardTypePermission(wildcardPackage);
        xStream.addPermission(permission);
        return XStreamSerializer.builder().xStream(xStream).build();
    }
}